<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-05-13 11:43:27
-->
<template>
  <el-cascader
    ref="refCascader"
    v-model="cascaderValue"
    :placeholder="getPlaceholder()"
    :options="addressOptions"
    :props="addressProps"
    :clearable="clearable"
    :="$attrs"
    @change="handleChange"
  />
</template>

<script setup>
// import dataList from 'province-city-china/dist/data.json'
import levelList from 'province-city-china/dist/level.json'
// import provinceList from 'province-city-china/dist/province.json'
// import cityList from 'province-city-china/dist/city.json'
// import hongkongList from 'province-city-china/dist/hongkong.json'
// import macauList from 'province-city-china/dist/macau.json'
// import areaList from 'province-city-china/dist/area.json'
// import townList from 'province-city-china/dist/town.json'
// console.log('levelList', levelList)
// console.log('townList', townList)

const props = defineProps({
  // 省市区街道的层级
  level: {
    type: Number,
    default: 4 // 1~4
  },
  placeholder: {
    type: String,
    default: ''
  },
  clearable: {
    type: Boolean,
    default: true
  },
  label: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['change'])
const refCascader = ref(null)
const cascaderValue = defineModel({
  type: Array,
  default: []
})

// 特殊的直辖市编码
const speCode1 = ['11', '12', '31', '50']
// 台湾省、港澳行政区
const speCode2 = ['71', '81', '82']
const speCode = [...speCode1, ...speCode2]
const addressOptions = ref([])
const addressProps = {
  label: 'name',
  value: 'code',
  lazy: true,
  lazyLoad(node, resolve) {
    const { level, data } = node
    let nodes = []
    // console.log('level, data', props.level, level, data)
    if (props.level > level) {
      // 特殊的直辖市编码处理
      if ((speCode.includes(data.province) && level === 2) || level === 3) {
        // nodes = getTownList(data.province, data.city, data.area)
      }
      // console.log('nodes', nodes)
    }
    resolve(nodes)
  }
}

onMounted(() => {
  addressOptions.value = getCascaderList()
})

/**
 * 根据 levelList 生成 Cascader 级联选择器数据
 * @param {Array} dataList 当前层级的数据，默认为 levelList 的深拷贝
 * @param {number} i 当前处理的层级，从 1 开始
 * @returns {Array} 处理后的级联数据
 */
const getCascaderList = (
  dataList = JSON.parse(JSON.stringify(levelList)),
  i = 1
) => {
  return dataList.map(item => {
    const isSpecialCity = speCode.includes(item.province) // 是否为直辖市/特殊城市
    const shouldRecurse = props.level > (isSpecialCity ? i + 1 : i)
    const children = shouldRecurse
      ? getCascaderList(item.children || [], i + 1)
      : []

    const node = {
      ...item,
      leaf: speCode2.includes(item.province)
        ? !children.length
        : !children.length && props.level <= 3,
      children
    }

    return node
  })
}

// const getTownList = (province, city, area) => {
//   return JSON.parse(JSON.stringify(townList)).filter(item => {
//     if (
//       item.province === province &&
//       item.city === city &&
//       item.area === area
//     ) {
//       item.leaf = true
//       return true
//     }
//   })
// }

const getPlaceholder = _ => {
  return (
    props.placeholder ||
    g_rules.zhAndEnShowMsg(g_t('public.pleaseSelect'), props.label)
  )
}

const handleChange = value => {
  const checkedNode = refCascader.value.getCheckedNodes()[0]
  emit('change', {
    lastCode: value[value.length - 1] || '',
    value: value || [],
    pathLabels: checkedNode?.pathLabels || [],
    text: checkedNode?.text?.replace(/\s*/g, '') || ''
  })
}

defineExpose({
  refCascader
})
</script>

<style scoped lang="scss"></style>
